app.controller('UserCtrl', [
    '$scope', 'notification', 'userService', '$modal',
    function ($scope, notification, userService, $modal) {
        $scope.page = {
            index: 1,
            size: 10,
            total: 0
        };

        $scope.form = { phone: '' };

        $scope.userList = [];

        function load(index) {
            userService.getAllAsync($scope.form.phone, index || $scope.page.index, $scope.page.size)
                .then(function (result) {
                    $scope.userList = result.data;
                    $scope.page.total = result.total;
                    if (result.total == 0 && index == 1) {
                        notification.alert("没有查询到数据");
                    }
                }, notification.error);
        }

        $scope.$watch('page.index', function (newVal, oldVal) {
            load();
        });

        $scope.$watch('page.size', function (newVal, oldVal) {
            if (!newVal || newVal === oldVal) return;
            load();
        });


        $scope.search = function () {
            load(1);
        };

        $scope.lockToggle = function (user) {
            if (user.Id == $scope.app.user.Id && !user.LockoutEnabled) {
                notification.alert('请不要锁定自己');
                return;
            }
            userService.toggleLockAsync(user.Id)
                .then(function () {
                    user.LockoutEnabled = !user.LockoutEnabled;
                }, notification.error);
        };

        $scope.setRole = function (userId) {
            var modelInstance = $modal.open({
                templateUrl: 'tpl/sys/users-roles.html',
                backdrop: false,
                controller: [
                    '$scope', 'userService', 'notification',
                    function ($self, userService, notification) {

                        userService.getUserRolesAsync(userId)
                            .then(function (result) {
                                $self.roleList = result;
                            }, notification.error);

                        $self.miss = function () {
                            modelInstance.dismiss();
                        };

                        $self.toggleRole = function (role) {
                            userService.toggleRoleAsync(userId, role.Name)
                                .then(function (auth) {
                                    role.Authorized = auth;
                                }, notification.error);
                        };

                        $self.createRole=function(){
                            if(!$self.newRole || $self.newRole.trim()==''){
                                notification.alert('角色名不能为空');
                                return;
                            }
                            userService.createRoleAsync($self.newRole)
                                .then(function(){
                                    $self.roleList.push({
                                        Name:$self.newRole,
                                        Authorized:false
                                    })
                                }, notification.error);
                        };
                    }
                ]
            });
        };
    }
]);

app.factory('userService', [
    '$http', '$q',
    function ($http, $q) {
        var self = {};

        self.getAllAsync = function (phone, pageIndex, pageSize) {
            var q = $q.defer();
            $http({
                url: '/api/user',
                params: {
                    phone: phone,
                    pageIndex: pageIndex,
                    pageSize: pageSize
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    q.resolve({ total: result.Code, data: result.Data });
                } else {
                    q.reject(result.Message);
                }
            }).error(function (x) {
                q.reject('查询用户列表失败，请稍后再试');
                console.error(x);
            });
            return q.promise;
        };

        self.toggleLockAsync = function (userId) {
            var q = $q.defer();
            $http({
                method: 'POST',
                url: '/api/user/lock',
                params: {
                    userId: userId
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    q.resolve();
                } else {
                    q.reject(result.Message);
                }
            }).error(function (x) {
                q.reject('变更用户锁定状态失败，请稍后再试');
                console.error(x);
            });
            return q.promise;
        };

        self.toggleRoleAsync = function (userId, role) {
            var q = $q.defer();
            $http({
                method: 'POST',
                url: '/api/user/role',
                params: {
                    userId: userId,
                    role: role
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    q.resolve(result.Data);
                } else {
                    q.reject(result.Message);
                }
            }).error(function (x) {
                q.reject('变更用户角色失败，请稍后再试');
                console.error(x);
            });
            return q.promise;
        };

        self.getUserRolesAsync = function (userId) {
            var q = $q.defer();
            $http({
                url: '/api/user/role',
                params: {
                    userId: userId
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    q.resolve(result.Data);
                } else {
                    q.reject(result.Message);
                }
            }).error(function (x) {
                q.reject('获取用户角色失败，请稍后再试');
                console.error(x);
            });
            return q.promise;
        };

        self.createRoleAsync=function(newRole){
             var q = $q.defer();
            $http({
                method:'POST',
                url: '/api/user/role',
                params: {
                    role: newRole
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    q.resolve(result.Data);
                } else {
                    q.reject(result.Message);
                }
            }).error(function (x) {
                q.reject('创建角色失败，请稍后再试');
                console.error(x);
            });
            return q.promise;
        };

        return self;
    }
]);